package com.zzx.shiro.realm;

import com.zzx.shiro.entity.User;
import com.zzx.shiro.service.PermissionService;
import com.zzx.shiro.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * @ClassName: CustomRealm
 * @Description: 自定义Realm
 * @Author zhouzhixin
 * @Date 2021/9/13
 * @Version 1.0
 */
@Component
public class CustomRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;

    @Autowired
    PermissionService permissionService;

    /**
     * <p>权限验证方法</p>
     * @param principalCollection
     * @return org.apache.shiro.authz.AuthorizationInfo
     * @author zhouzhixin
     * @date 2021/9/15 17:41
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("-------权限验证方法--------");
        String username = String.valueOf(SecurityUtils.getSubject().getPrincipal());
        Set<String> permissions = permissionService.queryByUserName(username);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(permissions);
        return info;
    }

    /**
     * <p>身份认证方法</p>
     * @param authenticationToken
     * @return org.apache.shiro.authc.AuthenticationInfo
     * @author zhouzhixin
     * @date 2021/9/15 17:41
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("-------身份认证方法--------");
        String userName = (String) authenticationToken.getPrincipal();
        User user = userService.queryByUserName(userName);
        if (user == null) {
            return null;
        }
        // 密码
        String password = user.getPassword();
        // 密码盐
        String salt = user.getSalt();
        return new SimpleAuthenticationInfo(userName, password, ByteSource.Util.bytes(salt), getName());
    }

}
